package com.alit.face.koala.service.upload;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;

import com.alit.face.koala.projectvariable.PVK;
import com.litong.utils.projectvariable.PVU;

@Service
public class FileSaveSerivce {
  /**
   * @return
   * @eg upload/System.currentTimeMillis().extension
   */
  public String saveInputStream(InputStream inputStream, int length, String extension, Object object) {
    String imgDir = PVU.getValue(PVK.projectImgDir);
    String subDir = generateSubdir();
    String filename = getFilename(extension);
    String uri = getFileUri(subDir, filename);
    String folderPath = imgDir + File.separator + subDir;
    File folder = new File(folderPath);
    if (!folder.exists()) {
      folder.mkdirs();
    }
    String fullPath = folderPath + File.separator + filename;
    int bufferSize = 1024 * 1024;
    byte[] buffer = new byte[bufferSize];
    BufferedOutputStream outputStream = null;
    try {
      outputStream = new BufferedOutputStream(new FileOutputStream(fullPath));
      if ((length = inputStream.read(buffer, 0, bufferSize)) != -1) {
        outputStream.write(buffer, 0, length);
      }
    } catch (IOException e1) {
      e1.printStackTrace();
    } finally {
      IOUtils.closeQuietly(outputStream);
    }
    return uri;
  }

  /**
   * 根据年夜日时,生成子文件
   * @return
   */
  private String generateSubdir() {
    Calendar calendar = Calendar.getInstance();
    int year = calendar.get(Calendar.YEAR); // 获取年
    int month = calendar.get(Calendar.MONTH) + 1;// 获取月
    int day = calendar.get(Calendar.DAY_OF_MONTH); // 获取天
    int hour = calendar.get(Calendar.HOUR); // 获取小时
    return apppend(File.separator, year, month, day, hour);
  }

  private String apppend(String separator, int year, int month, int day, int hour) {
    String str = year + separator + month + separator + day + separator + hour;
    return str;
  }

  private String getFileUri(String subDir, String filename) {
    // 返回文件下载路径,不包含工程名称
    String imgDirName = PVU.getValue(PVK.projectUploadDirName);
    return imgDirName + File.separator + subDir + File.separator + filename;
  }

  public String getFilename(String extension) {
    long currentTimeMillis = System.currentTimeMillis();
    String fileName = currentTimeMillis + "." + extension;
    return fileName;
  }

}
